package model

import (
	"mlgmd.com/hearsay/base"
	"mlgmd.com/hearsay/entities"
	"mlgmd.com/hearsay/utils"
	"xorm.io/xorm"
)

type Reward struct {
	entities.Reward `xorm:"extends"`
	Creator         entities.User   `xorm:"extends" json:"creator"`
	HearsayList     []RewardHearsay `json:"hearsayList"`
	Comments        []RewardComment `json:"comments"`
}

func (Reward) Get(DB xorm.Interface, id int) (data Reward, err error) {
	defer base.Error(&err)
	base.Has(base.Must2(DB.ID(id).Get(&data.Reward)))
	base.Must2(DB.ID(data.CreatorId).Get(&data.Creator))
	base.Must(RewardHearsay{}.Query(DB, false).Where("rh.reward_id = ?", data.Id).Find(&data.HearsayList))
	data.HearsayList = utils.Foreach(data.HearsayList, base.MaskPtr[*RewardHearsay])
	base.Must(RewardComment{}.Query(DB).Where("c.target_id = ?", data.Id).Find(&data.Comments))
	cm := utils.MapByKey(data.Comments)
	for i, v := range data.Comments {
		if c, has := cm[v.ReplyToId]; has {
			data.Comments[i].ReplyTo = c.RewardComment
		}
	}
	return
}

func (Reward) Query(DB xorm.Interface) *xorm.Session {
	return DB.Table([]any{&entities.Reward{}, "r"}).
		Join("INNER", []any{&entities.User{}, "u"}, "u.id = r.creator_id")
}

type RewardHearsay struct {
	entities.Hearsay `xorm:"extends"`
	Creator          entities.User `xorm:"extends" json:"creator"`
	RewardId         int           `xorm:"reward_id"`
}

func (RewardHearsay) Query(DB xorm.Interface, deleted bool) *xorm.Session {
	s := DB.Table([]any{&entities.Hearsay{}, "h"}).
		Join("INNER", []any{&entities.User{}, "u"}, "u.id = h.creator_id").
		Join("INNER", []any{&entities.RewardHearsay{}, "rh"}, "rh.hearsay_id=h.id").
		Select("h.*, u.*, rh.reward_id")
	if !deleted {
		s = s.Where("h.deleted_time = 0")
	}
	return s
}

type RewardComment struct {
	entities.RewardComment `xorm:"extends"`
	Creator                entities.User          `xorm:"extends" json:"creator"`
	ReplyTo                entities.RewardComment `json:"replyTo"`
}

func (RewardComment) Query(DB xorm.Interface) *xorm.Session {
	return DB.Table([]any{&entities.RewardComment{}, "c"}).
		Join("INNER", []any{&entities.User{}, "u"}, "u.id = c.creator_id")
}
